package com.concurrency.example.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * condition和wait用法类似，不过它是由Lock构建出来的
 */
public class ConditionTest {
    public void conditionWait(Lock lock, Condition condition){
        lock.lock();
        try {
            condition.await();
            System.out.println("wait 已被唤醒");
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        finally {
            lock.unlock();
        }
    }
    public void conditionSignal(Lock lock, Condition condition){
        lock.lock();
        try{
            condition.signalAll();
        }
        finally{
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException{
        final ConditionTest conditionTest = new ConditionTest();
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(() -> conditionTest.conditionWait(lock, condition)).start();
        TimeUnit.SECONDS.sleep(4);
        new Thread(() -> conditionTest.conditionSignal(lock, condition)).start();
    }
}
